#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   ShowDiaLog
@Time    :   2023/03/14 22:39:56
@author  :   Eval
@Version :   1.0
@Describe:   显示游戏弹窗
'''
from lib.scripts.ui.font import *
from uuid import uuid4
from conf.GameLogin import *
from lib.scripts.GameInit import *
from lib.scripts.GC import *

class ShowDiaLog:
    windows:dict = {}
    tipsArr:list = []
    #控制是否触发了弹窗,暂时只能同时触发一个弹窗,后续有需要再说
    isActive = False
    main = None

    def __init__(self) -> None:
        pass
    
    @staticmethod
    def render():
        """渲染弹窗"""
        try:
            for dialog in ShowDiaLog.windows:
                item = ShowDiaLog.windows[dialog]
                ShowDiaLog.main.win.blit(item["win"],(275,100))
                ShowDiaLog.main.GameFont.render_lineText(320,120,item["title"],fontSize=18)
                ShowDiaLog.main.GameFont.render_multilineText(275,170,item["text"],item["w"])
                if not item["image"] is None:
                    item["image"].update(ShowDiaLog.main,275,110)

                # if item["close"]:  # 应该不会出现自动消失的弹窗, 先留着 预防万一
                #     item["time"] -= 1
                #     if item["time"] <= 0:
                #         del ShowDiaLog.windows[dialog]
                #         if not len(ShowDiaLog.windows):
                #             ShowDiaLog.isActive = False  # 弹窗关闭
                #         break

        except Exception as e:
            print_error(f"弹窗出现bug了,{e}")
            ShowDiaLog.windows.clear()
        finally:
            if not len(ShowDiaLog.windows):
                ShowDiaLog.isActive = False  # 弹窗关闭

    @staticmethod
    def renderTips():
        """渲染提示"""
        for index,tips in enumerate(ShowDiaLog.tipsArr):
            msgY = int(tips["h"])*index+(index*20)
            ShowDiaLog.main.win.blit(tips["win"],(5,msgY))
            ShowDiaLog.main.GameFont.render_lineText(15,msgY+8,tips["text"],fontSize=tips["h"])
            tips["time"] -= 1
            if tips["time"] <= 0:
                ShowDiaLog.tipsArr.remove(tips)

    @staticmethod
    def showDialog(w=300,close=True,title:str="标题",text="新消息",imageName:str=None)->str:
        """生成新的弹窗  close为真 则自动关闭"""
        if ShowDiaLog.isActive:
            return
        h = ShowDiaLog.main.GameFont.getTextHeight(text,w,18)
        if h < 200:
            h = 200
        ShowDiaLog.isActive = True  # 弹窗被激活
        window = pygame.Surface((w,h))
        window.set_alpha(220)
        window.fill((100,100,100))
        # 使用uuid作为消息的id,删除id的时候根据返回的id进行操作
        MKey = str(uuid4())

        ShowDiaLog.windows[MKey] = {
            "win":window,
            "time":200,
            "rect":window.get_rect(),
            "w":w,
            "h":h,
            "close":close
        }
        ShowDiaLog.updateDialog(MKey,title,text,imageName)
        # 将当前添加进来的消息索引返回到调用处,方便手动关闭弹窗
        return MKey
    
    @staticmethod
    def rmDialog(id:str):
        """根据传入进来的消息id进行移除"""
        if ShowDiaLog.windows.get(id):
            del ShowDiaLog.windows[id]
            return
        print_error("无法移除不存在的消息")

    @staticmethod
    def updateDialog(id:str,title:str="标题",text="新消息",imageName:str=None):
        """更新弹窗内容,解决多次触发对话时,弹窗需要关闭在重新生成的不流畅效果"""
        # 如果有图像
        tipImg =  None
        if not imageName is None:
            if imageName.lower() == "hero":
                tipImg = ShowDiaLog.main.hero.imageUI
            else:
                for K in GC.GC_SourceMgr:
                    BName = GC.GC_SourceMgr[K].get("name")
                    if BName is None: continue
                    if BName == imageName:
                        tipImg = BlockSprite(GC.GC_GameSurfaceCache.get(GC.GC_SourceMgr[K]["type"]),GC.GC_SourceMgr[K])
                        break
        if ShowDiaLog.windows.get(id):
            ShowDiaLog.windows[id]["title"] = title
            ShowDiaLog.windows[id]["image"] = tipImg
            ShowDiaLog.windows[id]["text"] = text
            return
        print_error("无法更新不存在的消息")


        
    @staticmethod
    def showTips(text="新消息",fontSize:int = 14,time:int=200)->str:
        """生成气泡提示, 不可手动关闭, 根据时间进行消失"""
        w = ShowDiaLog.main.GameFont.getTextWidth(text,fontSize)
        # window = pygame.Surface((w,fontSize+10))
        # window.set_alpha(220)
        # window.fill((100,100,100))
        # 最多显示5条,太多了影响美观
        if len(ShowDiaLog.tipsArr) >= 5:
            ShowDiaLog.tipsArr.pop(0)
        bg = GC.loadSurface("msgBG_2.png").copy()
        bg = pygame.transform.smoothscale(bg,(w+20,fontSize+20))
        ShowDiaLog.tipsArr.append({
            "win":bg,
            "time":time,
            "w":w,
            "h":fontSize,
            "text":text
        })